/*
* simple autocomplete
*/
(function($){
  
  var target = '[data-autocpt=autocomplete]'
    , Autocomplete = function (element) {
        var $el = $(element);
		$el.on('keyup.autocomplete.data-api', this.keyup)
	
		$('html').on('keyup.autocomplete.data-api', function () {
          $el.parent().removeClass('autocpt-open')
        })
      },
      openTimer;

  //for keyup 
  Autocomplete.api = {};

  Autocomplete.prototype = {

    constructor: Autocomplete
	, keyup: function (e) {

      var $this = $(this)
        , $parent
        , isActive

      if ($this.is('.disabled, :disabled')) return

      if (/(38|40|27)/.test(e.keyCode)) return

      openTimer = setTimeout(function(){

        if(openTimer)
          clearTimeout(openTimer);

        $parent = getParent($this)[0];
        //clearAutoCompleteList();
        var apiMethod = $this.data('autocptapi'),
            val = $.trim($this.val());

        if(!Autocomplete.api[apiMethod]){
          $parent.addClass('autocpt-open')
          $this.focus();
        }else{
          Autocomplete.api[apiMethod].apply(Autocomplete,[$this,val,function(data){
            var $target = $parent.find('[role=autocomplete-list]')
            if(typeof data ==='string'){
              $target.html(data);
            }else{

              var i=0,l=data.length,ret = [];

              if(data && l > 0){
                for(;i<l;i++){
                  ret.push('<li><a href="#" data-val="'+data[i].val+'"'+(data[i].checked?' class="checked"':'')+'>'+data[i].txt+'</a></li>');
                }
                $target.html(ret.join(''));
              }
            }

            $parent.addClass('autocpt-open');
            $this.focus();

          }]);
        }

      },30);
    
      return false
    },
    keydown: function (e) {
      var $this
        , $items
        , $active
        , $parent
        , isActive
        , index
        ,checkedItem
        ,$item

      if (!/(38|40|27)/.test(e.keyCode)) return

      $this = $(this)

      //$this.blur()

      e.preventDefault()
      e.stopPropagation()

      if ($this.is('.disabled, :disabled')) return

      $parent = getParent($this)[0]

      isActive = $parent.hasClass('autocpt-open')

      // if ((isActive && e.keyCode == 13)){
      //   // $parent.find(target).val($('[role=autocomplete-list] li a.checked').data('val'));
      //   clearAutoCompleteList();
      //   return;
      // }

      $items = $('[role=autocomplete-list] li a', $parent)

      if (!$items.length) return

      checkedItem = $items.filter('.checked');
      index = $items.index(checkedItem)||0;

	
      if (e.keyCode == 38 ) index--                                        // up
      if (e.keyCode == 40 ) index++                        // down
      
      if(index>$items.length-1)
        index = 0

      if(index<0)
        index = $items.length-1

      checkedItem.removeClass('checked select');


      $item = $items.eq(index);
      
      $item.addClass('checked select');

      val  = $item.data('val');
	  
	  if(val && val!=''){
		$parent.find(target).val($parent.find('[role=autocomplete-list] li a.checked').data('val'));
        // clearAutoCompleteList();
      }

    },
    autoInsert:function(e){
      e.preventDefault();
      e.stopPropagation();

      $this = $(this),
      val  = $this.data('val');

	  if(val && val!=''){
        $parent = getParent($this.parent().parent())[0];

        $parent.find(target).val(val);
        clearAutoCompleteList();
      }
    }
  }

  Autocomplete.api.clearAutoCompleteList = clearAutoCompleteList;

  function clearAutoCompleteList() {
    var parents = getParent($(target));
      $(parents).each(function(i,item){
		$(item).removeClass('autocpt-open');
	  })
  }

  function getParent($this) {
	var $parents = []; 
    $this.each(function(i,item){
        var $item = $(item),
            selector = $(item).attr('data-target')
          , $parent
            
        if (!selector) {
            selector = $item.attr('href')
            selector = selector && /#/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
        }   

        $parent = $(selector)
        $parent.length || ($parent = $item.parent());
            
        $parents.push($parent);
    }); 
    return $parents
  }
  $.autocompleteUiApi = Autocomplete.api;

  $.fn.autocomplete = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('autocpt')
      if (!data) $this.data('autocpt', (data = new Autocomplete(this)))
      if (typeof option == 'string') data[option].call($this)
    })
  }

  $.fn.autocomplete.Constructor = Autocomplete


  $(function () {

    $('html')
      .on('click', clearAutoCompleteList);

    $('body')
      .on('click' , '[data-toggle=dropdown]', clearAutoCompleteList)
      .on('keydown',target+',[role=autocomplete-list]',Autocomplete.prototype.keydown)
      .on('keyup', target, Autocomplete.prototype.keyup)
	  .on('mousedown','[role=autocomplete-list] a',Autocomplete.prototype.autoInsert)
  })
})(jQuery);
